package com.cdream.basic.java8.io.aiochat;

import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.SelectionKey;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author cdream
 * @date 2022/8/16
 */
@Slf4j
public class ChatClient {
    private static final Integer PORT = 18080;
    private static final String HOST = "localhost";
    private static final String QUIT = "QUIT";
    private static AsynchronousSocketChannel sc = null;
    public static void main(String[] args) {
        try {
            sc = AsynchronousSocketChannel.open();
            Future<Void> connect = sc.connect(new InetSocketAddress(HOST, PORT));
            connect.get();
            while (true){
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String line = br.readLine();
                ByteBuffer wrap = ByteBuffer.wrap(line.getBytes());
                Future<Integer> write = sc.write(wrap);
                write.get();
                wrap.clear();
                wrap.flip();
                Future<Integer> read = sc.read(wrap);
                read.get();
                String string = new String(wrap.array());
                System.out.println(string);
                wrap.clear();
            }
        } catch (IOException | InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(sc);
        }
    }

    private static void handlers(SelectionKey selectionKey) throws IOException {
        // 连接就绪

    }

}
